<?php
/**
 * @author yuanyitian
 * @date 2024/8/26 22:29
 */

namespace api\wechat;

use utils\base64_to_file;
use utils\oss;
use utils\redis;
use utils\WXBizDataCrypt;

class user
{

    //普通登录
    public function login($data)
    {
        $res = file_get_contents($GLOBALS["wechat_baseurl"] . "sns/jscode2session?appid=" . $GLOBALS["wechat_appid"] . "&secret=" . $GLOBALS["wechat_secret"] . "&grabt_type=authorization_code&js_code=" . $data["code"]);
        $res = json_decode($res, true);
        $openid = $res["openid"];
        $session_key=$res['session_key'];
        $token = md5($openid);
        $token_session_key='session_key_'.$token;

        $redis = redis::con();
        $redis->setex($token, 1800, $openid);
        $redis->setex($token_session_key, 1800, $session_key);
        $redis->close();

        $info = [];
        $con = con();
        $wechat_user = mysqli_query($con, "select * from user where openid='$openid'");
        $wechat_user = mysqli_fetch_all($wechat_user, true);

        if (count($wechat_user) != 0) {
            $info = $wechat_user[0];
            if($info['phone']==0){
                $info['phone']='';
            }
            $info['money'] = sprintf('%.2f', $info['money'] / 100);


            $id=(int)$info['id'];
            $power=mysqli_query($con,"select * from user_power_config where user_id=$id and is_delete=1 and status=1 and check_status=1");
            $power=mysqli_fetch_all($power,true);


            //临时开放权限，若需权限控制，则改为false
            $info['type_1']=false;
            $info['type_2']=false;
            $info['type_3']=false;
            $info['type_4']=false;
            $info['type_5']=false;
            $info['type_7']=false;
            if(count($power)!=0){
                $power=array_unique(array_column($power,'type'));
                sort($power);
                for($i=0;$i<count($power);$i++){
                    switch ((int)$power[$i]){
                        case 1://骑手
                            $info['type_1']=true;
                            break;
                        case 2://任务发布人
                            $info['type_2']=true;
                            break;
                        case 3://任务接收人
                            $info['type_3']=true;
                            break;
                        case 4://任务验证人
                            $info['type_4']=true;
                            break;
                        case 5://会员
                            $info['type_5']=true;
                            break;
                        case 7://超级会员
                            $info['type_7']=true;
                            break;
                    }
                }
            }

        }else{
            mysqli_close($con);
            return out_not_login();
        }
        mysqli_close($con);
        return out_right(["token" => $token, "openid" => $openid, "userinfo" => $info]);
    }

    //超级会员扫码登录
    public function loginForSuper($data)
    {
        $res = file_get_contents($GLOBALS["wechat_baseurl"] . "sns/jscode2session?appid=" . $GLOBALS["wechat_appid"] . "&secret=" . $GLOBALS["wechat_secret"] . "&grabt_type=authorization_code&js_code=" . $data["code"]);
        $res = json_decode($res, true);
        $openid = $res["openid"];
        $session_key=$res['session_key'];
        $token = md5($openid);
        $token_session_key='session_key_'.$token;

        $redis = redis::con();
        $redis->setex($token, 1800, $openid);
        $redis->setex($token_session_key, 1800, $session_key);
        $redis->close();

        $info = [];
        $con = con();
        $wechat_user = mysqli_query($con, "select * from user where openid='$openid'");
        $wechat_user = mysqli_fetch_all($wechat_user, true);

        if (count($wechat_user) != 0) {
            $has_user=true;
            if((int)$wechat_user[0]['phone']>0){
                $has_phone=true;
                $phone=$wechat_user[0]['phone'];
            }else{
                $has_phone=false;
                $phone='';
            }
        }else{
            $has_user=false;
            $has_phone=false;
            $phone='';
        }
        mysqli_close($con);
        return out_right(["token" => $token, "openid" => $openid, "has_user" => $has_user,'has_phone'=>$has_phone,'phone'=>$phone]);
    }

    //超级会员申请手机号
    public function phoneForSuper($data)
    {
        $code = $data["code"];
        $openid = $data["openid"];
        $time=time();
        if(empty($code)){
            return out_error('必须授权手机号！');
        }
        $redis = redis::con();
        $token = $redis->get("mini_access_token");
        if (!$token) {
            $token = $this->get_token();
            $token = json_decode($token, true);
            $token = $token["data"];
        }

        $url = $GLOBALS["wechat_baseurl"] . "wxa/business/getuserphonenumber?access_token=" . $token;
        $res = http($url, "json", "POST", ["code" => $code]);
        if(!$res["phone_info"]['phoneNumber']){
            return out_error('网络异常！');
        }
        $phone = (int)$res["phone_info"]['phoneNumber'];

        $con = con();
        $user=mysqli_query($con,"select * from user where phone=$phone");
        $user=mysqli_fetch_all($user,true);
        if(count($user)===0){//不存在则自动创建
            mysqli_query($con,"insert into user(nickname,avatar,phone,is_vip,create_time,update_time,remark,openid) values('超级会员','https://luopingcn.oss-cn-chengdu.aliyuncs.com/goods/1/avatar.png',$phone,1,$time,$time,'扫超级会员码自动添加','$openid')");
            $user_id=(int)mysqli_insert_id($con);
            mysqli_query($con,"insert into user_power_config(user_id,type,create_time,update_time,remark) values($user_id,7,$time,$time,'扫超级会员码自动添加')");
        }else{//存在则绑定openid
            $user_id=(int)$user[0]['id'];
            mysqli_query($con,"update user set is_vip=1,openid='$openid',update_time=$time where id=$user_id");
            //查询超级会员权限
            $power=mysqli_query($con,"select * from user_power_config where user_id=$user_id and is_delete=1 and type=7");
            $power=mysqli_fetch_all($power,true);
            if(count($power)===0){//无超级会员权限则自动创建权限
                mysqli_query($con,"insert into user_power_config(user_id,type,create_time,update_time,remark) values($user_id,7,$time,$time,'扫超级会员码自动添加')");
            }
        }
        mysqli_close($con);

        return out_right();
    }

    //普通用户申请手机号
    public function phone($data)
    {
        $code = $data["code"];
        $redis = redis::con();
        $token = $redis->get("mini_access_token");
        if (!$token) {
            $token = $this->get_token();
            $token = json_decode($token, true);
            $token = $token["data"];
        }

        $url = $GLOBALS["wechat_baseurl"] . "wxa/business/getuserphonenumber?access_token=" . $token;
        $res = http($url, "json", "POST", ["code" => $code]);
        $res = $res["phone_info"];
        return out_right($res);
    }

    public function add_wechat_user($data)
    {
        $res = file_get_contents($GLOBALS["wechat_baseurl"] . "sns/jscode2session?appid=" . $GLOBALS["wechat_appid"] . "&secret=" . $GLOBALS["wechat_secret"] . "&grabt_type=authorization_code&js_code=" . $data["code"]);
        $res = json_decode($res, true);
        $openid = $res["openid"];
        $session_key=$res['session_key'];
        $token = md5($openid);
        $token_session_key='session_key_'.$token;

        $redis = redis::con();
        $redis->setex($token, 1800, $openid);
        $redis->setex($token_session_key, 1800, $session_key);
        $redis->close();

        $con = con();
        if(empty($data["file_name"])){
            $url='https://luopingcn.oss-cn-chengdu.aliyuncs.com/goods/1/avatar.png';
        }else{
            $file_name = basename($data["file_name"]);
            $file = base64_to_file::get_from_wechat($file_name, $data["file"]);
            $url = oss::upload("user/avatar" . $file["name"], $file["path"]);
            $url = $url["info"]["url"];
        }

        $time = time();
        $nickname = $data["nickname"];
        $name=$data['name'];
        $org=$data['org'];
        if(empty($nickname)){
            $nickname='普通用户';
        }else{
            $nickname = str_replace("\\", "\\\\", $nickname);
        }
        $phone = (int)$data["phone"];

        $data = mysqli_query($con, "select * from user where openid='$openid'");
        $data = mysqli_fetch_all($data, true);
        if (count($data) == 0) {
            mysqli_query($con, "insert into user(openid,nickname,avatar,phone,create_time,name,org) values('$openid','$nickname','$url',$phone,$time,'$name','$org')");
            $data = mysqli_query($con, "select * from user where openid='$openid'");
            $data = mysqli_fetch_all($data, true);
        }else{
            mysqli_query($con,"update user set nickname='$nickname',phone=$phone,avatar='$url' where openid='$openid'");
        }
        mysqli_close($con);


        //临时开放权限，若需权限控制，则改为false
        $data[0]['type_1']=false;
        $data[0]['type_2']=false;
        $data[0]['type_3']=false;
        $data[0]['type_4']=false;
        $data[0]['type_5']=false;
        $data[0]['type_7']=false;
        if($data[0]['phone']==0){
            $data[0]['phone']='';
        }

        $res=$data[0];
        $res['token']=$token;

        return out_right($res);
    }



    public function get_token()
    {
        $token = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $GLOBALS["wechat_appid"] . "&secret=" . $GLOBALS["wechat_secret"]);
        $token = json_decode($token, true);
        $token = $token["access_token"];
        $redis = redis::con();
        $redis->setex("mini_access_token", 7200, $token);
        $redis->close();
        return out_right($token);
    }

    //获取用户详情
    public function getInfo($data)
    {
        $openid = $data['openid'];
        $con = con();
        $info = mysqli_query($con, "select * from user where openid='$openid'");
        $info = mysqli_fetch_all($info, true);
        if (count($info) === 0) {
            mysqli_close($con);
            return out_not_login();
        }
        $id=(int)$info[0]['id'];
        $power=mysqli_query($con,"select * from user_power_config where user_id=$id and is_delete=1 and status=1 and check_status=1");
        $power=mysqli_fetch_all($power,true);

        //权限控制，若需要权限控制，则为false
        $info[0]['type_1']=false;
        $info[0]['type_2']=false;
        $info[0]['type_3']=false;
        $info[0]['type_4']=false;
        $info[0]['type_5']=false;
        $info[0]['type_7']=false;
//        $info[0]['type_1']=true;
//        $info[0]['type_2']=true;
//        $info[0]['type_3']=true;
//        $info[0]['type_4']=true;
        if(count($power)!=0){
            $power=array_unique(array_column($power,'type'));
            sort($power);
            for($i=0;$i<count($power);$i++){
                switch ((int)$power[$i]){
                    case 1:
                        $info[0]['type_1']=true;
                        break;
                    case 2:
                        $info[0]['type_2']=true;
                        break;
                    case 3:
                        $info[0]['type_3']=true;
                        break;
                    case 4:
                        $info[0]['type_4']=true;
                        break;
                    case 5:
                        $info[0]['type_5']=true;
                        break;
                    case 7:
                        $info[0]['type_7']=true;
                        break;
                }
            }
        }


        mysqli_close($con);
        $info[0]['money'] = sprintf('%.2f', $info[0]['money'] / 100);
        if($info[0]['phone']==0){
            $info[0]['phone']='';
        }
        return out_right($info[0]);


    }

    //微信数据解密
    public function decodeWechat($data){
        $appid = $GLOBALS['wechat_appid'];
        $encryptedData=$data['encryptedData'];
        $iv = $data['iv'];

        $redis = redis::con();
        $sessionKey=$redis->get('session_key_'.$data['login_token']);
        $redis->close();

        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $res );
        if($errCode===0){
            return out_right($res);
        }else{
            return out_error('错误码：'.$errCode);
        }

    }

    //支付界面获取用户数据，无用户则自动创建默认用户
    public function getInfoByPay($data){
        $openid = $data['openid'];
        $con = con();
        $info = mysqli_query($con, "select * from user where openid='$openid' order by `id` desc ");
        $info = mysqli_fetch_all($info, true);
        if(count($info)===0){
            mysqli_query($con,"insert into user(openid,nickname,avatar,) values()");
        }

    }

    //根据openid检测用户是否存在，不存在则自动创建用户，然后返回用户详情
    public function getUserInfo($openid){
        $time=time();
        $con = con();
        $info = mysqli_query($con, "select * from user where openid='$openid'");
        $info = mysqli_fetch_all($info, true);
        if(count($info)===0){
            mysqli_close($con);
            return out_not_login();
//            mysqli_query($con, "insert into user(openid,nickname,avatar,create_time) values('$openid','普通用户','https://luopingcn.oss-cn-chengdu.aliyuncs.com/goods/1/avatar.png',$time)");
//            $user_id=(int)mysqli_insert_id($con);
//            $info = mysqli_query($con, "select * from user where openid='$openid'");
//            $info=mysqli_fetch_all($info,true);
        }

        $info=$info[0];
        $user_id=(int)$info['id'];
        if($info['phone']==0){
            $info['phone']='';
        }

        $power=mysqli_query($con,"select * from user_power_config where user_id=$user_id and is_delete=1 and status=1 and check_status=1");
        $power=mysqli_fetch_all($power,true);


        //临时开放权限，若需权限控制，则为false
        $info['type_1']=false;
        $info['type_2']=false;
        $info['type_3']=false;
        $info['type_4']=false;
        $info['type_5']=false;
        $info['type_7']=false;
        if(count($power)!=0){
            $power=array_unique(array_column($power,'type'));
            sort($power);
            for($i=0;$i<count($power);$i++){
                switch ((int)$power[$i]){
                    case 1:
                        $info['type_1']=true;
                        break;
                    case 2:
                        $info['type_2']=true;
                        break;
                    case 3:
                        $info['type_3']=true;
                        break;
                    case 4:
                        $info['type_4']=true;
                        break;
                    case 5:
                        $info['type_5']=true;
                        break;
                    case 7:
                        $info['type_7']=true;
                        break;
                }
            }
        }

        mysqli_close($con);
        return $info;
    }

    //扫码自动成为会员
    public function becomeVip($data)
    {
        $res = file_get_contents($GLOBALS["wechat_baseurl"] . "sns/jscode2session?appid=" . $GLOBALS["wechat_appid"] . "&secret=" . $GLOBALS["wechat_secret"] . "&grabt_type=authorization_code&js_code=" . $data["code"]);
        $res = json_decode($res, true);
        $openid = $res["openid"];
        $session_key=$res['session_key'];
        $token = md5($openid);
        $token_session_key='session_key_'.$token;

        $redis = redis::con();
        $redis->setex($token, 1800, $openid);
        $redis->setex($token_session_key, 1800, $session_key);
        $redis->close();
        $time=time();

        $con = con();
        $wechat_user = mysqli_query($con, "select * from user where openid='$openid'");
        $wechat_user = mysqli_fetch_all($wechat_user, true);

        if (count($wechat_user) != 0) {//检测是否有该用户，没有则自动注册
            $user_id=(int)$wechat_user[0]['id'];
        }else{//创建新用户，切为普通会员
            mysqli_close($con);
            return out_not_login();
//            mysqli_query($con, "insert into user(openid,nickname,avatar,is_vip,create_time) values('$openid','普通用户','https://luopingcn.oss-cn-chengdu.aliyuncs.com/goods/1/avatar.png',1,$time)");
//            $user_id=(int)mysqli_insert_id($con);
        }
        $power=mysqli_query($con,"select * from user_power_config where user_id=$user_id and is_delete=1 and status=1 and type=5 ");
        $power=mysqli_fetch_all($power,true);
        if(count($power)===0){
            $res=mysqli_query($con,"insert into user_power_config(user_id,type,create_time,update_time,remark,check_status) values($user_id,5,$time,$time,'来源：会员码自动注册',0)");
            mysqli_close($con);
            if($res){
                return out_right('会员注册申请已提交！请等待管理员审核！');
            }else{
                return out_right('会员注册失败！');
            }
        }else{
            mysqli_close($con);
            $check_status=(int)$power[0]['check_status'];
            switch ($check_status) {
                case 0://待审核
                    $msg='您已提交过会员申请！请耐心等待管理员审核！';
                    break;
                case 1://审核已通过
                    $msg='您已是会员，禁止重复提交！';
                    break;
                case 2://审核已驳回
                    $msg='您提交的会员申请已驳回！禁止重复提交！';
                    break;
            }
            return out_right($msg);
        }
    }

}